//
//  SureIndentViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/4/15.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "SureIndentViewController.h"
#import "PayTypeViewController.h"
#import "ChoseAddressViewController.h"
#import "AddAddressViewController.h"
#import "SureIndentTableViewCell.h"
static NSString * cellIndentifier = @"SureIndentTableViewCell";

@interface SureIndentViewController ()<UITextViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *detailView;
@property (weak, nonatomic) IBOutlet UILabel *userAdressPhone;
@property (weak, nonatomic) IBOutlet UILabel *userName;
@property (weak, nonatomic) IBOutlet UILabel *userDetailAdress;
@property (strong, nonatomic) NSDictionary *adressDic;

@property (weak, nonatomic) IBOutlet UIButton *sureButton;



@end

@implementation SureIndentViewController


- (void)viewWillAppear:(BOOL)animated{
    if (_addressView.hidden == YES) {
        _detailView.frame =flexibleFrame(CGRectMake(0, 110, 320,CGRectGetHeight(_detailView.frame)), NO);
    }else{
     _detailView.frame =flexibleFrame(CGRectMake(0, 150, 320, CGRectGetHeight(_detailView.frame)), NO);
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hadPay) name:@"hadPay" object:@"1"];
    _adressDic = [NSDictionary dictionary];
    [self initViewlayout];
    [self queryDefaultMallShippingAddress];
    
}


- (void)initViewlayout{
     self.view.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.addressView];
    [self adaptiveViewLayout:self.detailView];
    
    
    
    _sureButton.layer.masksToBounds = YES;
    _sureButton.layer.cornerRadius = 4*VerticalRatio();

    if (_productDic) {
        _detailView.frame = flexibleFrame(CGRectMake(0, CGRectGetMinY(_detailView.frame)/VerticalRatio(), 320, 133+181+62), NO);
        _tableView.frame = flexibleFrame(CGRectMake(0, 23, 320, 181+62), NO);
        _sureButton.frame = flexibleFrame(CGRectMake(15, CGRectGetMaxY(_tableView.frame)/VerticalRatio()+50, 290, 40), NO);
        _scroView.contentSize = flexibleSize(CGSizeMake(0, CGRectGetMaxY(_detailView.frame)/VerticalRatio()), NO);
    }else if (_productArray){
        for (int i = 0; i<_productArray.count; i++) {
            NSMutableDictionary * dic = [_productArray[i] mutableCopy];
            NSMutableArray * rowsArray = [dic[@"mallCartDetail"] mutableCopy];
            for (int j = 0; j<rowsArray.count; j++) {
                NSString * key = [NSString stringWithFormat:@"%d%d",i,j];
                if (![_choseDic.allKeys containsObject:key]) {
                    [rowsArray removeObjectAtIndex:j];
                }
            }
            [dic setObject:rowsArray forKey:@"mallCartDetail"];
            [_productArray replaceObjectAtIndex:i withObject:dic];
            if (rowsArray.count == 0) {
                [_productArray removeObjectAtIndex:i];
            }
        }
        
        
        NSInteger sections = _productArray.count;
        NSInteger rows = 0;
        for (NSDictionary * dic in _productArray) {
            NSArray * array = dic[@"mallCartDetail"];
            rows +=array.count;
        }
        _detailView.frame = flexibleFrame(CGRectMake(0, CGRectGetMinY(_detailView.frame)/VerticalRatio(), 320, 133+181*sections+62*rows), NO);
        _tableView.frame = flexibleFrame(CGRectMake(0, 23, 320,181*sections+62*rows), NO);
        _sureButton.frame = flexibleFrame(CGRectMake(15, CGRectGetMaxY(_tableView.frame)/VerticalRatio()+50, 290, 40), NO);
        _scroView.contentSize = flexibleSize(CGSizeMake(0, CGRectGetMaxY(_detailView.frame)/VerticalRatio()), NO);
        
    }
    
    [_tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
}
#pragma mark == 查询默认收货地址
- (void)queryDefaultMallShippingAddress{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryDefaultMallShippingAddress withHttpType:@"POST" withTag:GS_GS_queryDefaultMallShippingAddress];
    
}
- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark   ===修改地址
- (IBAction)changeAddress:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SupplyChainStoryboard" bundle:nil];
    AddAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddAddress"];
    page.addressInfo = [_adressDic mutableCopy];
    page.endEditBlock = ^(NSString * delected){
        if ([delected isEqualToString:@"0"]) {
            [self getAddressInfo];
        }else{
            _addressView.hidden = YES;
        }
        
    };
    [[Common getNavigation]pushViewController:page];
    
}

#pragma mark  === 修改完地址后查询地址详情
- (void)getAddressInfo{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[NSString stringWithFormat:@"%@",_adressDic[@"msadId"]] forKey:@"msadId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryMallShippingAddressById withHttpType:@"POST" withTag:GS_GS_queryMallShippingAddressById];
}


#pragma mark   ====选择地址
- (IBAction)choseAddress:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SupplyChainStoryboard" bundle:nil];
    ChoseAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ChoseAddress"];
    page.choseAddress = ^(NSDictionary * dic){
        _adressDic = dic;
        _addressView.hidden = NO;
        _userName.text = dic[@"msadReceiverName"];
        _userAdressPhone.text = dic[@"msadMobileNo"];
        _userDetailAdress.numberOfLines = 0;
        _userDetailAdress.text = [NSString stringWithFormat:@"%@%@%@%@",dic[@"msadProvinceName"],dic[@"msadCityName"],dic[@"msadAreaName"],dic[@"msadAddr"]];
        [_userDetailAdress sizeToFit];
        _detailView.frame =flexibleFrame(CGRectMake(0, 150, 320, CGRectGetHeight(_detailView.frame)), NO);
    };
    [[Common getNavigation]pushViewController:page];
    
}

#pragma mark == 立即预约
- (IBAction)payhandel:(id)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    if (!_adressDic) {
        [CWHUDTips showLoadingTips:@"请添加收货地址信息"];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];

    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:_adressDic[@"msadId"] forKey:@"addressId"];

    if (_productDic) {//商品详情立即购买
        NSMutableDictionary * jsonDic = [NSMutableDictionary dictionary];
        NSMutableDictionary * resultDic = [NSMutableDictionary dictionary];
        NSMutableArray * storesArray = [NSMutableArray array];
        NSMutableDictionary * storeDic = [NSMutableDictionary dictionary];
        NSMutableArray * goodsArray = [NSMutableArray array];
        NSMutableDictionary * goodDic = [NSMutableDictionary dictionary];
        [goodDic setObject:_productDic[@"mgooId"] forKey:@"mgooId"];
        [goodsArray addObject:goodDic];
        [storeDic setObject:_storeId forKey:@"mstoId"];
        UITextView * textView = [self.view viewWithTag:100];
        [storeDic setObject:textView.text forKey:@"remark"];
        [storeDic setObject:goodsArray forKey:@"goods"];
        [storesArray addObject:storeDic];
        [resultDic setObject:storesArray forKey:@"store"];
        [jsonDic setObject:resultDic forKey:@"result"];
        
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:&parseError];
        NSString * jsonStr =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [dic setObject:jsonStr forKey:@"jsonStr"];
    }else{//购物车购买
        NSMutableDictionary * jsonDic = [NSMutableDictionary dictionary];
        NSMutableDictionary * resultDic = [NSMutableDictionary dictionary];
        NSMutableArray * storesArray = [NSMutableArray array];
        for (int i = 0;i<_productArray.count;i++) {
            NSDictionary * storedic = _productArray[i];
            NSMutableDictionary * storeDic = [NSMutableDictionary dictionary];
            NSArray * goodsarray = storedic[@"mallCartDetail"];
            NSMutableArray * goodsArray = [NSMutableArray array];
            for (NSDictionary * goodsdic in goodsarray) {
                NSMutableDictionary * goodDic = [NSMutableDictionary dictionary];
                [goodDic setObject:goodsdic[@"mallGoods"][@"mgooId"] forKey:@"mgooId"];
                [goodsArray addObject:goodDic];
            }
           [storeDic setObject:storedic[@"mstoId"] forKey:@"mstoId"];
            UITextView * textView = [self.view viewWithTag:100+i];
            [storeDic setObject:textView.text forKey:@"remark"];
            [storeDic setObject:goodsArray forKey:@"goods"];
            [storesArray addObject:storeDic];
            [resultDic setObject:storesArray forKey:@"store"];
            [jsonDic setObject:resultDic forKey:@"result"];
        }
        
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:&parseError];
        NSString * jsonStr =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [dic setObject:jsonStr forKey:@"jsonStr"];

    }
   
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_saveConfirmOrder withHttpType:@"POST" withTag:GS_GS_saveConfirmOrder];
    
}

//支付完成通知执行方法
- (void)hadPay{
    [self backBtn];
}


#pragma mark  ==== tableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 28*VerticalRatio();
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 153*VerticalRatio();
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 28), NO)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel * line = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 1), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.941 alpha:1.000];
    [view addSubview:line];
    
    //公司名称
    UILabel * companyName = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(14, 1, 300, 28), NO)];
    companyName.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    companyName.font = [UIFont systemFontOfSize:15*VerticalRatio()];
    if (_productDic) {
       companyName.text = _storeName;
    }else if (_productArray){
    companyName.text = [NSString stringWithFormat:@"%@",_productArray[section][@"mstoName"]];
    }
    [view addSubview:companyName];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 153), NO)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel * line = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 148, 320, 5), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.941 alpha:1.000];
    [view addSubview:line];
    
    //运费
    UILabel * transPrice = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(14, 10, 300, 15), NO)];
    transPrice.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    transPrice.font = [UIFont systemFontOfSize:15*VerticalRatio()];
    if (_productDic) {
        transPrice.text = [NSString stringWithFormat:@"运费:%@",_transPrice];
    }else if (_productArray){
        transPrice.text = [NSString stringWithFormat:@"￥运费:%.2f",[_productArray[section][@"mstoFreight"]floatValue]];
    }
    

    [view addSubview:transPrice];
    
    //备注
    UILabel * mark = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(14, 30, 300, 15), NO)];
    mark.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    mark.font = [UIFont systemFontOfSize:15*VerticalRatio()];
    mark.text = @"备注";
    [view addSubview:mark];
    
    UITextView * textView =[[UITextView alloc]initWithFrame:flexibleFrame(CGRectMake(14, 55, 292, 64), NO)];
    textView.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    textView.font =  [UIFont systemFontOfSize:15*VerticalRatio()];
    textView.tag = 100+section;
    textView.layer.masksToBounds = YES;
    textView.layer.borderWidth = 1;
    textView.layer.borderColor = [UIColor colorWithWhite:0.941 alpha:1.000].CGColor;
    textView.layer.cornerRadius = 3*VerticalRatio();
    [view addSubview:textView];
    
    
    //总计
    UILabel * totalPrice = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(220, 125, 100, 15), NO)];
    totalPrice.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    totalPrice.font = [UIFont systemFontOfSize:13*VerticalRatio()];
    
    NSString * price = @"";
    if (_productDic) {
        CGFloat pri = [_productDic[@"mgooPrice"]floatValue];
        CGFloat trans = [_transPrice floatValue];
        price = [NSString stringWithFormat:@"%.2f",pri+trans];
    }else if (_productArray){
        CGFloat pri = 0;
        NSDictionary * dic = _productArray[section];
            NSArray * array = dic[@"mallCartDetail"];
            for (NSDictionary * dict in array) {
                CGFloat pric = [dict[@"mallGoods"][@"mgooPrice"]floatValue];
                NSInteger num = [dict[@"mcdeCount"]integerValue];
                pri += pric*num;
            }
        
        
        CGFloat trans = [_productArray[section][@"mstoFreight"]floatValue];
        price = [NSString stringWithFormat:@"%.2f",pri+trans];
    }
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"总计:￥%@",price]];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15*VerticalRatio()] range:NSMakeRange(3, str.length-3)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.467 blue:0.004 alpha:1.000] range:NSMakeRange(3, str.length-3)];
    totalPrice.attributedText = str;
    [view addSubview:totalPrice];
    
    
    return view;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (_productDic) {
       return 1;
    }else if (_productArray){
        return _productArray.count;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_productDic) {
        return 1;
    }else if (_productArray){
        NSArray * array = _productArray[section][@"mallCartDetail"];
        return array.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 62*VerticalRatio();
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SureIndentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[SureIndentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    if (_productDic) {
        cell.goodsName.text = [NSString stringWithFormat:@"%@",_productDic[@"mgooName"]];
        cell.goodsType.text = [NSString stringWithFormat:@"规格:%@",_productDic[@"mgooSpecify"]];
        cell.goodsPrice.text = [NSString stringWithFormat:@"价格:￥%.2f",[_productDic[@"mgooPrice"]floatValue]];
        NSString * image = [NSString stringWithFormat:@"%@",_productDic[@"mgooImage"]];
        if (image.length>0) {
            [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
    }else if (_productArray){
        NSDictionary * dic = _productArray[indexPath.section][@"mallCartDetail"][indexPath.row];
        cell.goodsName.text = [NSString stringWithFormat:@"%@",dic[@"mallGoods"][@"mgooName"]];
        cell.goodsPrice.text = [NSString stringWithFormat:@"价格:￥%@",dic[@"mallGoods"][@"mgooPrice"]];
        cell.goodsType.text = [NSString stringWithFormat:@"规格:%@/块",dic[@"mallGoods"][@"mgooSpecify"]];
        NSString * image =  [NSString stringWithFormat:@"%@",dic[@"mallGoods"][@"mgooImage"]];
        if (image.length>0) {
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        
        cell.goodsNum.text = [NSString stringWithFormat:@"x%@",dic[@"mcdeCount"]];
       
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if (tag==GS_GS_queryDefaultMallShippingAddress || tag == GS_GS_queryMallShippingAddressById) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSDictionary * dic = database[@"result"];
            _adressDic = dic;
            if (![dic isEqual:[NSNull null]]) {
                _addressView.hidden = NO;
                 _detailView.frame =flexibleFrame(CGRectMake(0, 150, 320, CGRectGetHeight(_detailView.frame)), NO);
                _userName.text = dic[@"msadReceiverName"];
                _userAdressPhone.text = dic[@"msadMobileNo"];
                _userDetailAdress.numberOfLines = 0;
                _userDetailAdress.text = [NSString stringWithFormat:@"%@%@%@%@",dic[@"msadProvinceName"],dic[@"msadCityName"],dic[@"msadAreaName"],dic[@"msadAddr"]];
                [_userDetailAdress sizeToFit];
            }else{
                _addressView.hidden = YES;
            }
            
        }
    } else if (tag == GS_GS_saveConfirmOrder){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SupplyChainStoryboard" bundle:nil];
            PayTypeViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PayType"];
            page.payOrderPrice = database[@"result"][@"orderPrice"];
            page.payOrderName = @"中盘科技";
            page.payId = database[@"result"][@"orderNo"];
            page.orderFirstNo = database[@"result"][@"orderFirstNo"];
            page.payTypes = @"2";
//            page.paySuccessBlock = ^(){
//                [self backBtn];
//            };
            [[Common getNavigation]pushViewController:page completion:^{
                 [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            }];
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"hadPay" object:@"1"];
}

@end
